<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.doctor_name" placeholder="医生姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="getList()" />
      <el-select v-model="listQuery.subject_name" placeholder="所属科室" clearable style="width: 130px;margin-left: 30px" class="filter-item" filterable>
        <el-option v-for="(value, key) in departmentOptions" :key="key" :label="value" :value="value" />
      </el-select>
      <el-select v-model="listQuery.post_level" placeholder="职称" clearable class="filter-item" style="width: 130px;margin-left: 30px;margin-right: 30px" filterable>
        <el-option v-for="(value, key) in qualificationOptions" :key="key" :label="value" :value="value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getList()">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh-left" @click="reset()">
        重置
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" prop="id" align="center" width="50px">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.doctor_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生照片" width="130px" align="center">
        <template slot-scope="{row}">
          <img :src="`${baseUrl}${row.photo}`" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column label="医生年龄" min-width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.age || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学历学位" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.education || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始工作时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.work_date || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="毕业学校" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.university || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职称" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.post_level || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.major || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属科室" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.subject_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="挂号费用" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.order_money || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生简介" width="160px" align="center">
        <template slot-scope="{row}">
          <el-tooltip effect="dark" :content="row.about_me" placement="top">
            <span class="ellipsis">{{ row.about_me || '-' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" icon="el-icon-thumb" @click="showReserve(row)">
            挂号
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="医生放号情况" :visible.sync="dialogFormVisible">
      <el-table
        :key="tableKey2"
        v-loading="listLoading1"
        :data="doctorSchedule"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="序号" prop="id" align="center" width="80px">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医生姓名" width="130px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.doctor_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="就诊日期" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.appointment_date }}</span>
          </template>
        </el-table-column>
        <el-table-column label="就诊时段" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.timeSlotDescription }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可用号数" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.available_slots }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="147px" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-popconfirm title="您确认要预约该医生的号吗？" @onConfirm="reserveOnline(row)" @confirm="reserveOnline(row)">
              <el-button slot="reference" :disabled="row.state === '1' || row.state === '4'" type="primary" size="mini">
                {{ row.state_description }}
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getAllDoctor, reserveOnline, doctorReserveTable } from '@/api/reserve'
import waves from '@/directive/waves' // waves directive
import { departmentOptions, qualificationOptions, timeSlotOptions, stateOptions } from './mockData'
import moment from 'moment'
import { Message } from 'element-ui'

export default {
  name: 'ReservePage',
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      tableKey2: 1,
      list: null,
      total: 0,
      listLoading: true,
      listLoading1: true,
      // 主页面查询
      listQuery: {
        doctor_name: undefined,
        subject_name: undefined,
        post_level: undefined
      },
      // 限定选择今天、明天、后天3天进行挂号
      pickerOptions: {
        disabledDate(time) {
          const today = new Date()
          const tomorrow = new Date(today)
          tomorrow.setDate(today.getDate() + 1)
          const dayAfterTomorrow = new Date(today)
          dayAfterTomorrow.setDate(today.getDate() + 2)
          // 设置今天的时间范围为00:00:00到23:59:59
          const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())

          return time.getTime() < todayStart.getTime() || time.getTime() > dayAfterTomorrow.getTime()
        }
      },
      stateOptions,
      timeSlotOptions,
      // 所属科室枚举
      departmentOptions,
      // 医生职称枚举
      qualificationOptions,
      // 医生列表模拟
      doctorSchedule: undefined,
      dialogFormVisible: false,
      baseUrl: 'https://101.70.156.105:28847/media/'
    }
  },
  // 创建页面时，先获取数据，再渲染页面
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // 筛选时也是重新发送请求到后端请求数据
      getAllDoctor(this.listQuery).then(response => {
        this.list = response.doctors
      })
      // Just to simulate the time of the request
      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)
    },
    // 重置
    reset() {
      this.listQuery = {
        doctor_name: undefined,
        subject_name: undefined,
        post_level: undefined
      }
      this.getList() // 重新发送请求
    },
    // 转换返回数据的格式
    transformData(rawData, row) {
      const result = []
      for (const date in rawData) {
        for (const timeSlot in rawData[date]) {
          // 获取当前的日期和时间
          const currentDate = new Date().toISOString().split('T')[0]
          const currentHour = new Date().getHours()
          const availableSlots = rawData[date][timeSlot] // 可预约数量
          const timeSlotDescription = this.timeSlotOptions[timeSlot] // 就诊时间段映射
          const [startTime, endTime] = timeSlotDescription.split('-').map(time => time.split(':').map(Number))
          const nowTime = date === currentDate && currentHour >= startTime[0] && currentHour < endTime[0] // 现场挂号
          const isPastTime = date === currentDate && currentHour > startTime[0] // 过期
          let state = '3' // 3 -> 预约挂号
          if (nowTime) { // 2 -> 现场挂号
            state = '2'
          } else if (isPastTime) { // 3 -> 已过期
            state = '1'
          } else if (availableSlots === 0) { // 4 -> 已满
            state = '4'
          }
          result.push({
            doctor_id: row.id,
            doctor_name: row.doctor_name, // 假设医生姓名固定为医生A
            appointment_date: date,
            time_slot: timeSlot,
            timeSlotDescription: timeSlotDescription,
            available_slots: availableSlots, // 可预约数量
            state: state,
            state_description: this.stateOptions[state] // 状态描述
          })
        }
      }
      return result
    },
    // 点击挂号获取医生挂号时间表，展示该医生挂号弹窗
    showReserve(row) {
      const params = {
        doctor_id: row.id
      }
      this.listLoading1 = true
      doctorReserveTable(params).then(response => {
        const rawData = response
        this.doctorSchedule = this.transformData(rawData, row).slice(0, 12)
        this.dialogFormVisible = true
      })
      setTimeout(() => {
        this.listLoading1 = false
      }, 1.5 * 1000)
    },
    // 线上预约挂号
    reserveOnline(row) {
      const params = {
        patient_id: localStorage.getItem('user_id'),
        doctor_id: row.doctor_id,
        appointment_date: row.appointment_date,
        time_slot: row.time_slot
      }
      reserveOnline(params).then(response => {
        Message({
          message: response.message,
          type: 'success',
          duration: 3 * 1000
        })
        this.doctorSchedule = null
        this.dialogFormVisible = false
        this.getList()
      })
    },
    // 格式化日期
    formattedDate(date) {
      return moment(date).format('YYYY-MM-DD')
    }
  }
}
</script>

<style scoped>
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
</style>
